﻿using PeiYue.IRepository.Base;
using PeiYue.IServices.ERP;
using PeiYue.IServices.Sys;
using PeiYue.Model.Dto.Sys;
using PeiYue.Model.ERPModels;
using PeiYue.Model.Models;
using PeiYue.Model.Models.Crm;
using PeiYue.Model.Models.Sys;
using PeiYue.Services.BASE;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace PeiYue.Services.ERP
{
    public class ImportShopServices : BaseServices<ErpShop>, IImportShopServices
    {
        IBaseRepository<ErpShop> _dal;
        IBaseRepository<sysUserInfo> _userDal;
        IBaseRepository<ShopDao> _shopDal;
        IBaseRepository<AccountDao> _accountDal;
        IDicHeaderService _dicHeaderService;
        public ImportShopServices(IBaseRepository<ErpShop> dal,
            IBaseRepository<sysUserInfo> userDal,
            IBaseRepository<ShopDao> shopDal,
            IBaseRepository<AccountDao> accountDal,
            IDicHeaderService dicHeaderService
            )
        {
            this._dal = dal;
            base.BaseDal = dal;
            this._userDal = userDal;
            this._shopDal = shopDal;
            this._accountDal = accountDal;
            this._dicHeaderService = dicHeaderService;
        }
        /// <summary>
        /// 把ERP门店数据导入OMS
        /// </summary>
        /// <param name="isAll">true全部导入,false增量导入</param>
        /// <returns></returns>
        public async Task ImportShopFromERP(bool isAll = false)
        {
            List<ErpShop> shopList = new List<ErpShop>();
            var shopId = 0;
            if (isAll)
            {
                shopList = await _dal.Query("状态=1");
            }
            else
            {
                var list = await _shopDal.QuerySql("select top 1 * from oms_crm_customer_shop order by id desc ");
                var shopCode = string.Empty;
                if (list.Count > 0)
                {
                    shopCode = list.FirstOrDefault()?.codec;
                }
                var erpShopList = await _dal.Query(t => t.编号 == shopCode);
                if (erpShopList.Count == 0)
                {
                    shopList = await _dal.Query("状态=1");
                }
                else
                {
                    shopList = await _dal.Query("fid>" + erpShopList.FirstOrDefault().fID + " and 状态=1");
                }
            }
            sysUserInfo userDao = null;
            DicDetailDto dicDetail = null;
            foreach (var shop in shopList)
            {
                var shopDao = (await _shopDal.Query(p=>p.codec==shop.编号&&p.status==1)).FirstOrDefault();
                if (shopDao == null)
                {
                    shopDao = new ShopDao();
                }
                shopDao.codec = shop.编号;
                shopDao.namec = shop.名称;
                shopDao.names = shop.简称;
                shopDao.street= shop.送货地址;
                shopDao.contact = shop.联系人;
                shopDao.cellphone = shop.联系方式;
                shopDao.priority = string.IsNullOrWhiteSpace(shop.优先级) ? "" : shop.优先级;
                if (shop.合作状态 == "店铺停业")
                {
                    shopDao.business_status = 40;
                }
                else if (shop.合作状态 == "暂停合作")
                {
                    shopDao.business_status = 20;
                }
                else if (shop.合作状态 == "正常")
                {
                    shopDao.business_status = 10;
                }
                else if (shop.合作状态 == "终止合作")
                {
                    shopDao.business_status = 30;
                }
                userDao=(await _userDal.Query(p => p.uRealName == shop.制单人)).FirstOrDefault();
                if (userDao == null)
                {
                    shopDao.create_user = 0;
                }
                else
                {
                    shopDao.create_user = userDao.uID;
                }
                shopDao.create_time = Convert.ToDateTime(shop.制单日期);
                shopDao.update_time = DateTime.Now;
                shopDao.status = 1;
                shopDao.chef_contact = shop.厨师长姓名;
                shopDao.chef_cellphone= shop.厨师长电话;
                shopDao.shop_contact = shop.店长姓名;
                shopDao.shop_cellphone = shop.店长电话;
                shopDao.chain_flag = shop.是否连锁店=="是"?1:0;
                dicDetail=await _dicHeaderService.GetDicDetailByVal("cooking_style", shop.菜系分类);
                if (dicDetail != null)
                {
                    shopDao.cooking_style = Convert.ToInt32(dicDetail.k);
                }
                else
                {
                    shopDao.cooking_style = 0;
                }
                shopDao.area = GetNum(shop.店面面积);
                shopDao.seat = GetNum(shop.店面餐位数);
                userDao = (await _userDal.Query(p => p.uRealName == shop.开发销售)).FirstOrDefault();
                if (userDao == null)
                {
                    shopDao.dev_user = 0;
                }
                else
                {
                    shopDao.dev_user = userDao.uID;
                }
                userDao = (await _userDal.Query(p => p.uRealName == shop.维护销售)).FirstOrDefault();
                if (userDao == null)
                {
                    shopDao.mgr_user = 0;
                }
                else
                {
                    shopDao.mgr_user = userDao.uID;
                }
                shopDao.early_arrive_time = shop.最早送达时间;
                shopDao.late_arrive_time = shop.最晚送达时间;
                shopDao.purchase_old = shop.原有采购模式;
                dicDetail = await _dicHeaderService.GetDicDetailByVal("business_level", shop.客户级别);
                if (dicDetail != null)
                {
                    shopDao.business_level = Convert.ToInt32(dicDetail.k);
                }
                else
                {
                    shopDao.business_level = 0;
                }
                shopDao.prov_id = 1000000000001855;//默认上海
                shopDao.city_id = 1000000000001856;//默认市辖区
                shopDao.area_id = 1000000000001868;//默认浦东
                if (shopDao.id > 0)
                {
                   await _shopDal.Update(shopDao);
                }
                else
                {
                    //shopDao.id = await _shopDal.GenId();
                    shopId=await _shopDal.Add(shopDao);
                }

                //支付信息
                var accountDao = (await _accountDal.Query(p => p.shop_id == shopId && p.status == 1)).FirstOrDefault();
                if (accountDao == null)
                {
                    accountDao = new AccountDao();
                }
                accountDao.shop_id = shopId;
                accountDao.payment_method =0;
                accountDao.payment_type = 0;
                accountDao.invoice_types = 0;
                accountDao.pay_account = shop.支付方账号;
                accountDao.tax_number = shop.税务登记证号;
                accountDao.registr_address = shop.注册地址;
                accountDao.registr_phone = shop.注册电话;
                accountDao.opening_bank = shop.开户行;
                accountDao.bank_amount = shop.银行账号;
                accountDao.invoice_email = shop.电子发票邮箱;
                accountDao.invoice_contact = shop.纸质发票邮寄联系人;
                accountDao.invoice_phone = shop.纸质发票邮寄电话;
                accountDao.invoice_phone = shop.纸质发票邮寄电话;
                accountDao.amount_12m = GetNum(shop.年营业额);
                accountDao.amount_6m= GetNum(shop.店面过去6个月平均营业额);
                accountDao.amount_6m_sc = GetNum(shop.店面过去6个月平均采购额食材);
                accountDao.amount_6m_hc = GetNum(shop.店面过去6个月平均采购额耗材);
                accountDao.amount_6m_js = GetNum(shop.店面过去6个月平均采购额酒水饮料);
                if (accountDao.id > 0)
                {
                    await _accountDal.Update(accountDao);
                }
                else
                {
                   // accountDao.id = await _accountDal.GenId();
                    await _accountDal.Add(accountDao);
                }
            }
        }
        private int GetNum(string str)
        {
            if (string.IsNullOrWhiteSpace(str)) return 0;
            Regex r = new Regex("\\d+\\.?\\d*");
            bool ismatch = r.IsMatch(str);
            if (!ismatch)
            {
                return 0;
            }
            MatchCollection mc = r.Matches(str);
            return Convert.ToInt32(Convert.ToDecimal(mc[0].Value));
        }
    }
}
